home *** CD-ROM | disk | FTP | other *** search
/ Maximum CD 2009 May / maximum-cd-2009-05.iso / DiscContents / Firefox Setup 3.0.6.exe / nonlocalized / components / WebContentConverter.js < prev   
Encoding:
Text File  |  2009-01-19  |  33.2 KB  |  995 lines

  1. //@line 39 "e:\fx19rel\WINNT_5.2_Depend\mozilla\browser\components\feeds\src\WebContentConverter.js"
  2.  
  3. Components.utils.import("resource://gre/modules/XPCOMUtils.jsm");
  4.  
  5. const Cc = Components.classes;
  6. const Ci = Components.interfaces;
  7. const Cr = Components.results;
  8.  
  9. function LOG(str) {
  10.   dump("*** " + str + "\n");
  11. }
  12.  
  13. const WCCR_CONTRACTID = "@mozilla.org/embeddor.implemented/web-content-handler-registrar;1";
  14. const WCCR_CLASSID = Components.ID("{792a7e82-06a0-437c-af63-b2d12e808acc}");
  15. const WCCR_CLASSNAME = "Web Content Handler Registrar";
  16.  
  17. const WCC_CLASSID = Components.ID("{db7ebf28-cc40-415f-8a51-1b111851df1e}");
  18. const WCC_CLASSNAME = "Web Service Handler";
  19.  
  20. const TYPE_MAYBE_FEED = "application/vnd.mozilla.maybe.feed";
  21. const TYPE_ANY = "*/*";
  22.  
  23. const PREF_CONTENTHANDLERS_AUTO = "browser.contentHandlers.auto.";
  24. const PREF_CONTENTHANDLERS_BRANCH = "browser.contentHandlers.types.";
  25. const PREF_SELECTED_WEB = "browser.feeds.handlers.webservice";
  26. const PREF_SELECTED_ACTION = "browser.feeds.handler";
  27. const PREF_SELECTED_READER = "browser.feeds.handler.default";
  28. const PREF_HANDLER_EXTERNAL_PREFIX = "network.protocol-handler.external";
  29. const PREF_ALLOW_DIFFERENT_HOST = "gecko.handlerService.allowRegisterFromDifferentHost";
  30.  
  31. const STRING_BUNDLE_URI = "chrome://browser/locale/feeds/subscribe.properties";
  32.  
  33. const NS_ERROR_MODULE_DOM = 2152923136;
  34. const NS_ERROR_DOM_SYNTAX_ERR = NS_ERROR_MODULE_DOM + 12;
  35.  
  36. function WebContentConverter() {
  37. }
  38. WebContentConverter.prototype = {
  39.   convert: function WCC_convert() { },
  40.   asyncConvertData: function WCC_asyncConvertData() { },
  41.   onDataAvailable: function WCC_onDataAvailable() { },
  42.   onStopRequest: function WCC_onStopRequest() { },
  43.   
  44.   onStartRequest: function WCC_onStartRequest(request, context) {
  45.     var wccr = 
  46.         Cc[WCCR_CONTRACTID].
  47.         getService(Ci.nsIWebContentConverterService);
  48.     wccr.loadPreferredHandler(request);
  49.   },
  50.   
  51.   QueryInterface: function WCC_QueryInterface(iid) {
  52.     if (iid.equals(Ci.nsIStreamConverter) ||
  53.         iid.equals(Ci.nsIStreamListener) ||
  54.         iid.equals(Ci.nsISupports))
  55.       return this;
  56.     throw Cr.NS_ERROR_NO_INTERFACE;
  57.   }
  58. };
  59.  
  60. var WebContentConverterFactory = {
  61.   createInstance: function WCCF_createInstance(outer, iid) {
  62.     if (outer != null)
  63.       throw Cr.NS_ERROR_NO_AGGREGATION;
  64.     return new WebContentConverter().QueryInterface(iid);
  65.   },
  66.     
  67.   QueryInterface: function WCC_QueryInterface(iid) {
  68.     if (iid.equals(Ci.nsIFactory) ||
  69.         iid.equals(Ci.nsISupports))
  70.       return this;
  71.     throw Cr.NS_ERROR_NO_INTERFACE;
  72.   }
  73. };
  74.  
  75. function ServiceInfo(contentType, uri, name) {
  76.   this._contentType = contentType;
  77.   this._uri = uri;
  78.   this._name = name;
  79. }
  80. ServiceInfo.prototype = {
  81.   /**
  82.    * See nsIHandlerApp
  83.    */
  84.   get name() {
  85.     return this._name;
  86.   },
  87.   
  88.   /**
  89.    * See nsIHandlerApp
  90.    */
  91.   equals: function SI_equals(aHandlerApp) {
  92.     if (!aHandlerApp)
  93.       throw Cr.NS_ERROR_NULL_POINTER;
  94.  
  95.     if (aHandlerApp instanceof Ci.nsIWebContentHandlerInfo &&
  96.         aHandlerApp.contentType == this.contentType &&
  97.         aHandlerApp.uri == this.uri)
  98.       return true;
  99.  
  100.     return false;
  101.   },
  102.  
  103.   /**
  104.    * See nsIWebContentHandlerInfo
  105.    */
  106.   get contentType() {
  107.     return this._contentType;
  108.   },
  109.  
  110.   /**
  111.    * See nsIWebContentHandlerInfo
  112.    */
  113.   get uri() {
  114.     return this._uri;
  115.   },
  116.  
  117.   /**
  118.    * See nsIWebContentHandlerInfo
  119.    */
  120.   getHandlerURI: function SI_getHandlerURI(uri) {
  121.     return this._uri.replace(/%s/gi, encodeURIComponent(uri));
  122.   },
  123.   
  124.   QueryInterface: function SI_QueryInterface(iid) {
  125.     if (iid.equals(Ci.nsIWebContentHandlerInfo) ||
  126.         iid.equals(Ci.nsISupports))
  127.       return this;
  128.     throw Cr.NS_ERROR_NO_INTERFACE;
  129.   }
  130. };
  131.  
  132. function WebContentConverterRegistrar() {}
  133.  
  134. WebContentConverterRegistrar.prototype = {
  135.   get stringBundle() {
  136.     var sb = Cc["@mozilla.org/intl/stringbundle;1"].
  137.               getService(Ci.nsIStringBundleService).
  138.               createBundle(STRING_BUNDLE_URI);
  139.     delete WebContentConverterRegistrar.prototype.stringBundle;
  140.     return WebContentConverterRegistrar.prototype.stringBundle = sb;
  141.   },
  142.  
  143.   _getFormattedString: function WCCR__getFormattedString(key, params) {
  144.     return this.stringBundle.formatStringFromName(key, params, params.length);
  145.   },
  146.   
  147.   _getString: function WCCR_getString(key) {
  148.     return this.stringBundle.GetStringFromName(key);
  149.   },
  150.  
  151.   _contentTypes: { },
  152.  
  153.   /**
  154.    * Track auto handlers for various content types using a content-type to 
  155.    * handler map.
  156.    */
  157.   _autoHandleContentTypes: { },
  158.  
  159.   /**
  160.    * See nsIWebContentConverterService
  161.    */
  162.   getAutoHandler: 
  163.   function WCCR_getAutoHandler(contentType) {
  164.     contentType = this._resolveContentType(contentType);
  165.     if (contentType in this._autoHandleContentTypes)
  166.       return this._autoHandleContentTypes[contentType];
  167.     return null;
  168.   },
  169.   
  170.   /**
  171.    * See nsIWebContentConverterService
  172.    */
  173.   setAutoHandler:
  174.   function WCCR_setAutoHandler(contentType, handler) {
  175.     if (handler && !this._typeIsRegistered(contentType, handler.uri))
  176.       throw Cr.NS_ERROR_NOT_AVAILABLE;
  177.       
  178.     contentType = this._resolveContentType(contentType);
  179.     this._setAutoHandler(contentType, handler);
  180.     
  181.     var ps = 
  182.         Cc["@mozilla.org/preferences-service;1"].
  183.         getService(Ci.nsIPrefService);
  184.     var autoBranch = ps.getBranch(PREF_CONTENTHANDLERS_AUTO);
  185.     if (handler)
  186.       autoBranch.setCharPref(contentType, handler.uri);
  187.     else if (autoBranch.prefHasUserValue(contentType))
  188.       autoBranch.clearUserPref(contentType);
  189.      
  190.     ps.savePrefFile(null);
  191.   },
  192.   
  193.   /**
  194.    * Update the internal data structure (not persistent)
  195.    */
  196.   _setAutoHandler:
  197.   function WCCR__setAutoHandler(contentType, handler) {
  198.     if (handler) 
  199.       this._autoHandleContentTypes[contentType] = handler;
  200.     else if (contentType in this._autoHandleContentTypes)
  201.       delete this._autoHandleContentTypes[contentType];
  202.   },
  203.   
  204.   /**
  205.    * See nsIWebContentConverterService
  206.    */
  207.   getWebContentHandlerByURI:
  208.   function WCCR_getWebContentHandlerByURI(contentType, uri) {
  209.     var handlers = this.getContentHandlers(contentType, { });
  210.     for (var i = 0; i < handlers.length; ++i) {
  211.       if (handlers[i].uri == uri) 
  212.         return handlers[i];
  213.     }
  214.     return null;
  215.   },
  216.   
  217.   /**
  218.    * See nsIWebContentConverterService
  219.    */
  220.   loadPreferredHandler: 
  221.   function WCCR_loadPreferredHandler(request) {
  222.     var channel = request.QueryInterface(Ci.nsIChannel);
  223.     var contentType = this._resolveContentType(channel.contentType);
  224.     var handler = this.getAutoHandler(contentType);
  225.     if (handler) {
  226.       request.cancel(Cr.NS_ERROR_FAILURE);
  227.       
  228.       var webNavigation = 
  229.           channel.notificationCallbacks.getInterface(Ci.nsIWebNavigation);
  230.       webNavigation.loadURI(handler.getHandlerURI(channel.URI.spec), 
  231.                             Ci.nsIWebNavigation.LOAD_FLAGS_NONE, 
  232.                             null, null, null);
  233.     }      
  234.   },
  235.   
  236.   /**
  237.    * See nsIWebContentConverterService
  238.    */
  239.   removeProtocolHandler: 
  240.   function WCCR_removeProtocolHandler(aProtocol, aURITemplate) {
  241.     var eps = Cc["@mozilla.org/uriloader/external-protocol-service;1"].
  242.               getService(Ci.nsIExternalProtocolService);
  243.     var handlerInfo = eps.getProtocolHandlerInfo(aProtocol);
  244.     var handlers =  handlerInfo.possibleApplicationHandlers;
  245.     for (let i = 0; i < handlers.length; i++) {
  246.       try { // We only want to test web handlers
  247.         let handler = handlers.queryElementAt(i, Ci.nsIWebHandlerApp);
  248.         if (handler.uriTemplate == aURITemplate) {
  249.           handlers.removeElementAt(i);
  250.           var hs = Cc["@mozilla.org/uriloader/handler-service;1"].
  251.                    getService(Ci.nsIHandlerService);
  252.           hs.store(handlerInfo);
  253.           return;
  254.         }
  255.       } catch (e) { /* it wasn't a web handler */ }
  256.     }
  257.   },
  258.   
  259.   /**
  260.    * See nsIWebContentConverterService
  261.    */
  262.   removeContentHandler: 
  263.   function WCCR_removeContentHandler(contentType, uri) {
  264.     function notURI(serviceInfo) {
  265.       return serviceInfo.uri != uri;
  266.     }
  267.   
  268.     if (contentType in this._contentTypes) {
  269.       this._contentTypes[contentType] = 
  270.         this._contentTypes[contentType].filter(notURI);
  271.     }
  272.   },
  273.   
  274.   /**
  275.    *
  276.    */
  277.   _mappings: { 
  278.     "application/rss+xml": TYPE_MAYBE_FEED,
  279.     "application/atom+xml": TYPE_MAYBE_FEED,
  280.   },
  281.   
  282.   /**
  283.    * These are types for which there is a separate content converter aside 
  284.    * from our built in generic one. We should not automatically register
  285.    * a factory for creating a converter for these types.
  286.    */
  287.   _blockedTypes: {
  288.     "application/vnd.mozilla.maybe.feed": true,
  289.   },
  290.   
  291.   /**
  292.    * Determines the "internal" content type based on the _mappings.
  293.    * @param   contentType
  294.    * @returns The resolved contentType value. 
  295.    */
  296.   _resolveContentType: 
  297.   function WCCR__resolveContentType(contentType) {
  298.     if (contentType in this._mappings)
  299.       return this._mappings[contentType];
  300.     return contentType;
  301.   },
  302.  
  303.   _makeURI: function(aURL, aOriginCharset, aBaseURI) {
  304.     var ioService = Components.classes["@mozilla.org/network/io-service;1"]
  305.                               .getService(Components.interfaces.nsIIOService);
  306.     return ioService.newURI(aURL, aOriginCharset, aBaseURI);
  307.   },
  308.  
  309.   _checkAndGetURI:
  310.   function WCCR_checkAndGetURI(aURIString, aContentWindow)
  311.   {
  312.     try {
  313.       var uri = this._makeURI(aURIString);
  314.     } catch (ex) {
  315.       // not supposed to throw according to spec
  316.       return; 
  317.     }
  318.  
  319.     // For security reasons we reject non-http(s) urls (see bug 354316),
  320.     // we may need to revise this once we support more content types
  321.     // XXX this should be a "security exception" according to spec, but that
  322.     // isn't defined yet.
  323.     if (uri.scheme != "http" && uri.scheme != "https")
  324.       throw("Permission denied to add " + uri.spec + " as a content or protocol handler");
  325.  
  326.     // We also reject handlers registered from a different host (see bug 402287)
  327.     // The pref allows us to test the feature
  328.     var pb = Cc["@mozilla.org/preferences-service;1"].getService(Ci.nsIPrefBranch);
  329.     if ((!pb.prefHasUserValue(PREF_ALLOW_DIFFERENT_HOST) ||
  330.          !pb.getBoolPref(PREF_ALLOW_DIFFERENT_HOST)) &&
  331.         aContentWindow.location.hostname != uri.host)
  332.       throw("Permission denied to add " + uri.spec + " as a content or protocol handler");
  333.  
  334.     // If the uri doesn't contain '%s', it won't be a good handler
  335.     if (uri.spec.indexOf("%s") < 0)
  336.       throw NS_ERROR_DOM_SYNTAX_ERR; 
  337.  
  338.     return uri;
  339.   },
  340.  
  341.   /**
  342.    * Determines if a web handler is already registered.
  343.    *
  344.    * @param aProtocol
  345.    *        The scheme of the web handler we are checking for.
  346.    * @param aURITemplate
  347.    *        The URI template that the handler uses to handle the protocol.
  348.    * @return true if it is already registered, false otherwise.
  349.    */
  350.   _protocolHandlerRegistered:
  351.   function WCCR_protocolHandlerRegistered(aProtocol, aURITemplate) {
  352.     var eps = Cc["@mozilla.org/uriloader/external-protocol-service;1"].
  353.               getService(Ci.nsIExternalProtocolService);
  354.     var handlerInfo = eps.getProtocolHandlerInfo(aProtocol);
  355.     var handlers =  handlerInfo.possibleApplicationHandlers;
  356.     for (let i = 0; i < handlers.length; i++) {
  357.       try { // We only want to test web handlers
  358.         let handler = handlers.queryElementAt(i, Ci.nsIWebHandlerApp);
  359.         if (handler.uriTemplate == aURITemplate)
  360.           return true;
  361.       } catch (e) { /* it wasn't a web handler */ }
  362.     }
  363.     return false;
  364.   },
  365.  
  366.   /**
  367.    * See nsIWebContentHandlerRegistrar
  368.    */
  369.   registerProtocolHandler: 
  370.   function WCCR_registerProtocolHandler(aProtocol, aURIString, aTitle, aContentWindow) {
  371.     LOG("registerProtocolHandler(" + aProtocol + "," + aURIString + "," + aTitle + ")");
  372.     
  373.     // First, check to make sure this isn't already handled internally (we don't
  374.     // want to let them take over, say "chrome").
  375.     var ios = Cc["@mozilla.org/network/io-service;1"].
  376.               getService(Ci.nsIIOService);
  377.     var handler = ios.getProtocolHandler(aProtocol);
  378.     if (!(handler instanceof Ci.nsIExternalProtocolHandler)) {
  379.       // This is handled internally, so we don't want them to register
  380.       // XXX this should be a "security exception" according to spec, but that
  381.       // isn't defined yet.
  382.       throw("Permission denied to add " + aURIString + "as a protocol handler");
  383.     }
  384.  
  385.     // check if it is in the black list
  386.     var pb = Cc["@mozilla.org/preferences-service;1"].getService(Ci.nsIPrefBranch);
  387.     var allowed;
  388.     try {
  389.       allowed = pb.getBoolPref(PREF_HANDLER_EXTERNAL_PREFIX + "." + aProtocol);
  390.     }
  391.     catch (e) {
  392.       allowed = pb.getBoolPref(PREF_HANDLER_EXTERNAL_PREFIX + "-default");
  393.     }
  394.     if (!allowed) {
  395.       // XXX this should be a "security exception" according to spec
  396.       throw("Not allowed to register a protocol handler for " + aProtocol);
  397.     }
  398.  
  399.     var uri = this._checkAndGetURI(aURIString, aContentWindow);
  400.  
  401.     var buttons, message;
  402.     if (this._protocolHandlerRegistered(aProtocol, uri.spec))
  403.       message = this._getFormattedString("protocolHandlerRegistered",
  404.                                          [aTitle, aProtocol]);
  405.     else {
  406.       // Now Ask the user and provide the proper callback
  407.       message = this._getFormattedString("addProtocolHandler",
  408.                                          [aTitle, uri.host, aProtocol]);
  409.       var fis = Cc["@mozilla.org/browser/favicon-service;1"].
  410.                 getService(Ci.nsIFaviconService);
  411.       var notificationIcon = fis.getFaviconLinkForIcon(uri);
  412.       var notificationValue = "Protocol Registration: " + aProtocol;
  413.       var addButton = {
  414.         label: this._getString("addProtocolHandlerAddButton"),
  415.         accessKey: this._getString("addHandlerAddButtonAccesskey"),
  416.         protocolInfo: { protocol: aProtocol, uri: uri.spec, name: aTitle },
  417.  
  418.         callback:
  419.         function WCCR_addProtocolHandlerButtonCallback(aNotification, aButtonInfo) {
  420.           var protocol = aButtonInfo.protocolInfo.protocol;
  421.           var uri      = aButtonInfo.protocolInfo.uri;
  422.           var name     = aButtonInfo.protocolInfo.name;
  423.  
  424.           var handler = Cc["@mozilla.org/uriloader/web-handler-app;1"].
  425.                         createInstance(Ci.nsIWebHandlerApp);
  426.           handler.name = name;
  427.           handler.uriTemplate = uri;
  428.  
  429.           var eps = Cc["@mozilla.org/uriloader/external-protocol-service;1"].
  430.                     getService(Ci.nsIExternalProtocolService);
  431.           var handlerInfo = eps.getProtocolHandlerInfo(protocol);
  432.           handlerInfo.possibleApplicationHandlers.appendElement(handler, false);
  433.  
  434.           // Since the user has agreed to add a new handler, chances are good
  435.           // that the next time they see a handler of this type, they're going
  436.           // to want to use it.  Reset the handlerInfo to ask before the next
  437.           // use.
  438.           handlerInfo.alwaysAskBeforeHandling = true;
  439.  
  440.           var hs = Cc["@mozilla.org/uriloader/handler-service;1"].
  441.                    getService(Ci.nsIHandlerService);
  442.           hs.store(handlerInfo);
  443.         }
  444.       };
  445.       buttons = [addButton];
  446.     }
  447.  
  448.     var browserWindow = this._getBrowserWindowForContentWindow(aContentWindow);
  449.     var browserElement = this._getBrowserForContentWindow(browserWindow, aContentWindow);
  450.     var notificationBox = browserWindow.getBrowser().getNotificationBox(browserElement);
  451.     notificationBox.appendNotification(message,
  452.                                        notificationValue,
  453.                                        notificationIcon,
  454.                                        notificationBox.PRIORITY_INFO_LOW,
  455.                                        buttons);
  456.   },
  457.  
  458.   /**
  459.    * See nsIWebContentHandlerRegistrar
  460.    * If a DOM window is provided, then the request came from content, so we
  461.    * prompt the user to confirm the registration.
  462.    */
  463.   registerContentHandler: 
  464.   function WCCR_registerContentHandler(aContentType, aURIString, aTitle, aContentWindow) {
  465.     LOG("registerContentHandler(" + aContentType + "," + aURIString + "," + aTitle + ")");
  466.  
  467.     // We only support feed types at present.
  468.     // XXX this should be a "security exception" according to spec, but that
  469.     // isn't defined yet.
  470.     var contentType = this._resolveContentType(aContentType);
  471.     if (contentType != TYPE_MAYBE_FEED)
  472.       return;
  473.  
  474.     if (aContentWindow) {
  475.       var uri = this._checkAndGetURI(aURIString, aContentWindow);
  476.   
  477.       var browserWindow = this._getBrowserWindowForContentWindow(aContentWindow);
  478.       var browserElement = this._getBrowserForContentWindow(browserWindow, aContentWindow);
  479.       var notificationBox = browserWindow.getBrowser().getNotificationBox(browserElement);
  480.       this._appendFeedReaderNotification(uri, aTitle, notificationBox);
  481.     }
  482.     else
  483.       this._registerContentHandler(contentType, aURIString, aTitle);
  484.   },
  485.  
  486.   /**
  487.    * Returns the browser chrome window in which the content window is in
  488.    */
  489.   _getBrowserWindowForContentWindow:
  490.   function WCCR__getBrowserWindowForContentWindow(aContentWindow) {
  491.     return aContentWindow.QueryInterface(Ci.nsIInterfaceRequestor)
  492.                          .getInterface(Ci.nsIWebNavigation)
  493.                          .QueryInterface(Ci.nsIDocShellTreeItem)
  494.                          .rootTreeItem
  495.                          .QueryInterface(Ci.nsIInterfaceRequestor)
  496.                          .getInterface(Ci.nsIDOMWindow)
  497.                          .wrappedJSObject;
  498.   },
  499.  
  500.   /**
  501.    * Returns the <xul:browser> element associated with the given content
  502.    * window.
  503.    *
  504.    * @param aBrowserWindow
  505.    *        The browser window in which the content window is in.
  506.    * @param aContentWindow
  507.    *        The content window. It's possible to pass a child content window
  508.    *        (i.e. the content window of a frame/iframe).
  509.    */
  510.   _getBrowserForContentWindow:
  511.   function WCCR__getBrowserForContentWindow(aBrowserWindow, aContentWindow) {
  512.     // This depends on pseudo APIs of browser.js and tabbrowser.xml
  513.     aContentWindow = aContentWindow.top;
  514.     var browsers = aBrowserWindow.getBrowser().browsers;
  515.     for (var i = 0; i < browsers.length; ++i) {
  516.       if (browsers[i].contentWindow == aContentWindow)
  517.         return browsers[i];
  518.     }
  519.   },
  520.  
  521.   /**
  522.    * Appends a notifcation for the given feed reader details.
  523.    *
  524.    * The notification could be either a pseudo-dialog which lets
  525.    * the user to add the feed reader:
  526.    * [ [icon] Add %feed-reader-name% (%feed-reader-host%) as a Feed Reader?  (Add) [x] ]
  527.    *
  528.    * or a simple message for the case where the feed reader is already registered:
  529.    * [ [icon] %feed-reader-name% is already registered as a Feed Reader             [x] ]
  530.    *
  531.    * A new notification isn't appended if the given notificationbox has a
  532.    * notification for the same feed reader.
  533.    *
  534.    * @param aURI
  535.    *        The url of the feed reader as a nsIURI object
  536.    * @param aName
  537.    *        The feed reader name as it was passed to registerContentHandler
  538.    * @param aNotificationBox
  539.    *        The notification box to which a notification might be appended
  540.    * @return true if a notification has been appended, false otherwise.
  541.    */
  542.   _appendFeedReaderNotification:
  543.   function WCCR__appendFeedReaderNotification(aURI, aName, aNotificationBox) {
  544.     var uriSpec = aURI.spec;
  545.     var notificationValue = "feed reader notification: " + uriSpec;
  546.     var notificationIcon = aURI.prePath + "/favicon.ico";
  547.  
  548.     // Don't append a new notification if the notificationbox
  549.     // has a notification for the given feed reader already
  550.     if (aNotificationBox.getNotificationWithValue(notificationValue))
  551.       return false;
  552.  
  553.     var buttons, message;
  554.     if (this.getWebContentHandlerByURI(TYPE_MAYBE_FEED, uriSpec))
  555.       message = this._getFormattedString("handlerRegistered", [aName]);
  556.     else {
  557.       message = this._getFormattedString("addHandler", [aName, aURI.host]);
  558.       var self = this;
  559.       var addButton = {
  560.         _outer: self,
  561.         label: self._getString("addHandlerAddButton"),
  562.         accessKey: self._getString("addHandlerAddButtonAccesskey"),
  563.         feedReaderInfo: { uri: uriSpec, name: aName },
  564.  
  565.         /* static */
  566.         callback:
  567.         function WCCR__addFeedReaderButtonCallback(aNotification, aButtonInfo) {
  568.           var uri = aButtonInfo.feedReaderInfo.uri;
  569.           var name = aButtonInfo.feedReaderInfo.name;
  570.           var outer = aButtonInfo._outer;
  571.  
  572.           // The reader could have been added from another window mean while
  573.           if (!outer.getWebContentHandlerByURI(TYPE_MAYBE_FEED, uri))
  574.             outer._registerContentHandler(TYPE_MAYBE_FEED, uri, name);
  575.  
  576.           // avoid reference cycles
  577.           aButtonInfo._outer = null;
  578.  
  579.           return false;
  580.         }
  581.       };
  582.       buttons = [addButton];
  583.     }
  584.  
  585.     aNotificationBox.appendNotification(message,
  586.                                         notificationValue,
  587.                                         notificationIcon,
  588.                                         aNotificationBox.PRIORITY_INFO_LOW,
  589.                                         buttons);
  590.     return true;
  591.   },
  592.  
  593.   /**
  594.    * Save Web Content Handler metadata to persistent preferences. 
  595.    * @param   contentType
  596.    *          The content Type being handled
  597.    * @param   uri
  598.    *          The uri of the web service
  599.    * @param   title
  600.    *          The human readable name of the web service
  601.    *
  602.    * This data is stored under:
  603.    * 
  604.    *    browser.contentHandlers.type0 = content/type
  605.    *    browser.contentHandlers.uri0 = http://www.foo.com/q=%s
  606.    *    browser.contentHandlers.title0 = Foo 2.0alphr
  607.    */
  608.   _saveContentHandlerToPrefs: 
  609.   function WCCR__saveContentHandlerToPrefs(contentType, uri, title) {
  610.     var ps = 
  611.         Cc["@mozilla.org/preferences-service;1"].
  612.         getService(Ci.nsIPrefService);
  613.     var i = 0;
  614.     var typeBranch = null;
  615.     while (true) {
  616.       typeBranch = 
  617.         ps.getBranch(PREF_CONTENTHANDLERS_BRANCH + i + ".");
  618.       try {
  619.         typeBranch.getCharPref("type");
  620.         ++i;
  621.       }
  622.       catch (e) {
  623.         // No more handlers
  624.         break;
  625.       }
  626.     }
  627.     if (typeBranch) {
  628.       typeBranch.setCharPref("type", contentType);
  629.       var pls = 
  630.           Cc["@mozilla.org/pref-localizedstring;1"].
  631.           createInstance(Ci.nsIPrefLocalizedString);
  632.       pls.data = uri;
  633.       typeBranch.setComplexValue("uri", Ci.nsIPrefLocalizedString, pls);
  634.       pls.data = title;
  635.       typeBranch.setComplexValue("title", Ci.nsIPrefLocalizedString, pls);
  636.     
  637.       ps.savePrefFile(null);
  638.     }
  639.   },
  640.   
  641.   /**
  642.    * Determines if there is a type with a particular uri registered for the 
  643.    * specified content type already.
  644.    * @param   contentType
  645.    *          The content type that the uri handles
  646.    * @param   uri
  647.    *          The uri of the 
  648.    */
  649.   _typeIsRegistered: function WCCR__typeIsRegistered(contentType, uri) {
  650.     if (!(contentType in this._contentTypes))
  651.       return false;
  652.       
  653.     var services = this._contentTypes[contentType];
  654.     for (var i = 0; i < services.length; ++i) {
  655.       // This uri has already been registered
  656.       if (services[i].uri == uri)
  657.         return true;
  658.     }
  659.     return false;
  660.   },
  661.   
  662.   /**
  663.    * Gets a stream converter contract id for the specified content type.
  664.    * @param   contentType
  665.    *          The source content type for the conversion.
  666.    * @returns A contract id to construct a converter to convert between the 
  667.    *          contentType and *\/*.
  668.    */
  669.   _getConverterContractID: function WCCR__getConverterContractID(contentType) {
  670.     const template = "@mozilla.org/streamconv;1?from=%s&to=*/*";
  671.     return template.replace(/%s/, contentType);
  672.   },
  673.   
  674.   /**
  675.    * Register a web service handler for a content type.
  676.    * 
  677.    * @param   contentType
  678.    *          the content type being handled
  679.    * @param   uri
  680.    *          the URI of the web service
  681.    * @param   title
  682.    *          the human readable name of the web service
  683.    */
  684.   _registerContentHandler:
  685.   function WCCR__registerContentHandler(contentType, uri, title) {
  686.     this._updateContentTypeHandlerMap(contentType, uri, title);
  687.     this._saveContentHandlerToPrefs(contentType, uri, title);
  688.  
  689.     if (contentType == TYPE_MAYBE_FEED) {
  690.       // Make the new handler the last-selected reader in the preview page
  691.       // and make sure the preview page is shown the next time a feed is visited
  692.       var pb = Cc["@mozilla.org/preferences-service;1"].
  693.                getService(Ci.nsIPrefService).getBranch(null);
  694.       pb.setCharPref(PREF_SELECTED_READER, "web");
  695.   
  696.       var supportsString = 
  697.         Cc["@mozilla.org/supports-string;1"].
  698.         createInstance(Ci.nsISupportsString);
  699.         supportsString.data = uri;
  700.       pb.setComplexValue(PREF_SELECTED_WEB, Ci.nsISupportsString,
  701.                          supportsString);
  702.       pb.setCharPref(PREF_SELECTED_ACTION, "ask");
  703.       this._setAutoHandler(TYPE_MAYBE_FEED, null);
  704.     }
  705.   },
  706.  
  707.   /**
  708.    * Update the content type -> handler map. This mapping is not persisted, use
  709.    * registerContentHandler or _saveContentHandlerToPrefs for that purpose.
  710.    * @param   contentType
  711.    *          The content Type being handled
  712.    * @param   uri
  713.    *          The uri of the web service
  714.    * @param   title
  715.    *          The human readable name of the web service
  716.    */
  717.   _updateContentTypeHandlerMap: 
  718.   function WCCR__updateContentTypeHandlerMap(contentType, uri, title) {
  719.     if (!(contentType in this._contentTypes))
  720.       this._contentTypes[contentType] = [];
  721.  
  722.     // Avoid adding duplicates
  723.     if (this._typeIsRegistered(contentType, uri)) 
  724.       return;
  725.     
  726.     this._contentTypes[contentType].push(new ServiceInfo(contentType, uri, title));
  727.     
  728.     if (!(contentType in this._blockedTypes)) {
  729.       var converterContractID = this._getConverterContractID(contentType);
  730.       var cr = Components.manager.QueryInterface(Ci.nsIComponentRegistrar);
  731.       cr.registerFactory(WCC_CLASSID, WCC_CLASSNAME, converterContractID, 
  732.                          WebContentConverterFactory);
  733.     }
  734.   },
  735.   
  736.   /**
  737.    * See nsIWebContentConverterService
  738.    */
  739.   getContentHandlers: 
  740.   function WCCR_getContentHandlers(contentType, countRef) {
  741.     countRef.value = 0;
  742.     if (!(contentType in this._contentTypes))
  743.       return [];
  744.     
  745.     var handlers = this._contentTypes[contentType];
  746.     countRef.value = handlers.length;
  747.     return handlers;
  748.   },
  749.   
  750.   /**
  751.    * See nsIWebContentConverterService
  752.    */
  753.   resetHandlersForType: 
  754.   function WCCR_resetHandlersForType(contentType) {
  755.     // currently unused within the tree, so only useful for extensions; previous
  756.     // impl. was buggy (and even infinite-looped!), so I argue that this is a
  757.     // definite improvement
  758.     throw Cr.NS_ERROR_NOT_IMPLEMENTED;
  759.   },
  760.   
  761.   /**
  762.    * Registers a handler from the settings on a preferences branch.
  763.    *
  764.    * @param branch
  765.    *        an nsIPrefBranch containing "type", "uri", and "title" preferences
  766.    *        corresponding to the content handler to be registered
  767.    */
  768.   _registerContentHandlerWithBranch: function(branch) {
  769.     /**
  770.      * Since we support up to six predefined readers, we need to handle gaps 
  771.      * better, since the first branch with user-added values will be .6
  772.      * 
  773.      * How we deal with that is to check to see if there's no prefs in the 
  774.      * branch and stop cycling once that's true.  This doesn't fix the case
  775.      * where a user manually removes a reader, but that's not supported yet!
  776.      */
  777.     var vals = branch.getChildList("", {});
  778.     if (vals.length == 0)
  779.       return;
  780.  
  781.     try {
  782.       var type = branch.getCharPref("type");
  783.       var uri = branch.getComplexValue("uri", Ci.nsIPrefLocalizedString).data;
  784.       var title = branch.getComplexValue("title",
  785.                                          Ci.nsIPrefLocalizedString).data;
  786.       this._updateContentTypeHandlerMap(type, uri, title);
  787.     }
  788.     catch(ex) {
  789.       // do nothing, the next branch might have values
  790.     }
  791.   },
  792.  
  793.   /**
  794.    * Load the auto handler, content handler and protocol tables from 
  795.    * preferences.
  796.    */
  797.   _init: function WCCR__init() {
  798.     var ps = 
  799.         Cc["@mozilla.org/preferences-service;1"].
  800.         getService(Ci.nsIPrefService);
  801.  
  802.     var kids = ps.getBranch(PREF_CONTENTHANDLERS_BRANCH)
  803.                  .getChildList("", {});
  804.  
  805.     // first get the numbers of the providers by getting all ###.uri prefs
  806.     var nums = [];
  807.     for (var i = 0; i < kids.length; i++) {
  808.       var match = /^(\d+)\.uri$/.exec(kids[i]);
  809.       if (!match)
  810.         continue;
  811.       else
  812.         nums.push(match[1]);
  813.     }
  814.  
  815.     // sort them, to get them back in order
  816.     nums.sort(function(a, b) {return a - b;});
  817.  
  818.     // now register them
  819.     for (var i = 0; i < nums.length; i++) {
  820.       var branch = ps.getBranch(PREF_CONTENTHANDLERS_BRANCH + nums[i] + ".");
  821.       this._registerContentHandlerWithBranch(branch);
  822.     }
  823.  
  824.     // We need to do this _after_ registering all of the available handlers, 
  825.     // so that getWebContentHandlerByURI can return successfully.
  826.     try {
  827.       var autoBranch = ps.getBranch(PREF_CONTENTHANDLERS_AUTO);
  828.       var childPrefs = autoBranch.getChildList("", { });
  829.       for (var i = 0; i < childPrefs.length; ++i) {
  830.         var type = childPrefs[i];
  831.         var uri = autoBranch.getCharPref(type);
  832.         if (uri) {
  833.           var handler = this.getWebContentHandlerByURI(type, uri);
  834.           this._setAutoHandler(type, handler);
  835.         }
  836.       }
  837.     }
  838.     catch (e) {
  839.       // No auto branch yet, that's fine
  840.       //LOG("WCCR.init: There is no auto branch, benign");
  841.     }
  842.   },
  843.  
  844.   /**
  845.    * See nsIObserver
  846.    */
  847.   observe: function WCCR_observe(subject, topic, data) {
  848.     var os = 
  849.         Cc["@mozilla.org/observer-service;1"].
  850.         getService(Ci.nsIObserverService);
  851.     switch (topic) {
  852.     case "app-startup":
  853.       os.addObserver(this, "browser-ui-startup-complete", false);
  854.       break;
  855.     case "browser-ui-startup-complete":
  856.       os.removeObserver(this, "browser-ui-startup-complete");
  857.       this._init();
  858.       break;
  859.     }
  860.   },
  861.   
  862.   /**
  863.    * See nsIFactory
  864.    */
  865.   createInstance: function WCCR_createInstance(outer, iid) {
  866.     if (outer != null)
  867.       throw Cr.NS_ERROR_NO_AGGREGATION;
  868.     return this.QueryInterface(iid);
  869.   },
  870.  
  871.   /**
  872.    * See nsIClassInfo
  873.    */
  874.   getInterfaces: function WCCR_getInterfaces(countRef) {
  875.     var interfaces = 
  876.         [Ci.nsIWebContentConverterService, Ci.nsIWebContentHandlerRegistrar,
  877.          Ci.nsIObserver, Ci.nsIClassInfo, Ci.nsIFactory, Ci.nsISupports];
  878.     countRef.value = interfaces.length;
  879.     return interfaces;
  880.   },
  881.   getHelperForLanguage: function WCCR_getHelperForLanguage(language) {
  882.     return null;
  883.   },
  884.   contractID: WCCR_CONTRACTID,
  885.   classDescription: WCCR_CLASSNAME,
  886.   classID: WCCR_CLASSID,
  887.   implementationLanguage: Ci.nsIProgrammingLanguage.JAVASCRIPT,
  888.   flags: Ci.nsIClassInfo.DOM_OBJECT,
  889.   
  890.   /**
  891.    * See nsISupports
  892.    */
  893.   QueryInterface: XPCOMUtils.generateQI(
  894.      [Ci.nsIWebContentConverterService, 
  895.       Ci.nsIWebContentHandlerRegistrar,
  896.       Ci.nsIObserver,
  897.       Ci.nsIClassInfo,
  898.       Ci.nsIFactory,
  899.       Ci.nsISupports]),
  900.  
  901.   _xpcom_categories: [{
  902.     category: "app-startup",
  903.     service: true
  904.   }]
  905. };
  906.  
  907. function NSGetModule(cm, file) {
  908.   return XPCOMUtils.generateModule([WebContentConverterRegistrar]);
  909. }
  910.  
  911. //@line 44 "e:\fx19rel\WINNT_5.2_Depend\mozilla\toolkit\content\debug.js"
  912.  
  913. var EXPORTED_SYMBOLS = ["NS_ASSERT"];
  914.  
  915. var gTraceOnAssert = true;
  916.  
  917. /**
  918.  * This function provides a simple assertion function for JavaScript.
  919.  * If the condition is true, this function will do nothing.  If the
  920.  * condition is false, then the message will be printed to the console
  921.  * and an alert will appear showing a stack trace, so that the (alpha
  922.  * or nightly) user can file a bug containing it.  For future enhancements, 
  923.  * see bugs 330077 and 330078.
  924.  *
  925.  * To suppress the dialogs, you can run with the environment variable
  926.  * XUL_ASSERT_PROMPT set to 0 (if unset, this defaults to 1).
  927.  *
  928.  * @param condition represents the condition that we're asserting to be
  929.  *                  true when we call this function--should be
  930.  *                  something that can be evaluated as a boolean.
  931.  * @param message   a string to be displayed upon failure of the assertion
  932.  */
  933.  
  934. function NS_ASSERT(condition, message) {
  935.   if (condition)
  936.     return;
  937.  
  938.   var releaseBuild = true;
  939.   var defB = Components.classes["@mozilla.org/preferences-service;1"]
  940.                        .getService(Components.interfaces.nsIPrefService)
  941.                        .getDefaultBranch(null);
  942.   try {
  943.     switch (defB.getCharPref("app.update.channel")) {
  944.       case "nightly":
  945.       case "beta":
  946.       case "default":
  947.         releaseBuild = false;
  948.     }
  949.   } catch(ex) {}
  950.  
  951.   var caller = arguments.callee.caller;
  952.   var assertionText = "ASSERT: " + message + "\n";
  953.  
  954.   if (releaseBuild) {
  955.     // Just report the error to the console
  956.     Components.utils.reportError(assertionText);
  957.     return;
  958.   }
  959.  
  960.   // Otherwise, dump to stdout and launch an assertion failure dialog
  961.   dump(assertionText);
  962.  
  963.   var stackText = "";
  964.   if (gTraceOnAssert) {
  965.     stackText = "Stack Trace: \n";
  966.     var count = 0;
  967.     while (caller) {
  968.       stackText += count++ + ":" + caller.name + "(";
  969.       for (var i = 0; i < caller.arguments.length; ++i) {
  970.         var arg = caller.arguments[i];
  971.         stackText += arg;
  972.         if (i < caller.arguments.length - 1)
  973.           stackText += ",";
  974.       }
  975.       stackText += ")\n";
  976.       caller = caller.arguments.callee.caller;
  977.     }
  978.   }
  979.  
  980.   var environment = Components.classes["@mozilla.org/process/environment;1"].
  981.                     getService(Components.interfaces.nsIEnvironment);
  982.   if (environment.exists("XUL_ASSERT_PROMPT") &&
  983.       !parseInt(environment.get("XUL_ASSERT_PROMPT")))
  984.     return;
  985.  
  986.   var source = null;
  987.   if (this.window)
  988.     source = this.window;
  989.   var ps = Components.classes["@mozilla.org/embedcomp/prompt-service;1"].
  990.            getService(Components.interfaces.nsIPromptService);
  991.   ps.alert(source, "Assertion Failed", assertionText + stackText);
  992. }
  993. //@line 949 "e:\fx19rel\WINNT_5.2_Depend\mozilla\browser\components\feeds\src\WebContentConverter.js"
  994.  
  995.